package net.bwie.realtime.vehicle.job.VehicleWindowRealtimeStatus;

import com.alibaba.fastjson.JSON;
import net.bwie.realtime.jtp.common.utils.JdbcUtil;
import net.bwie.realtime.jtp.common.utils.KafkaUtil;
import net.bwie.realtime.vehicle.bean.VehicleData;
import net.bwie.realtime.vehicle.utils.DateTimeUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * 实时车辆状态监控
 * 该类主要用于处理车辆数据，通过Flink窗口函数实现实时监控车辆状态，并将结果写入ClickHouse数据库
 *
 * @Author: FuHe
 * @Date: 2025/5/27
 */
public class VehicleWindowRealtimeStatus {
    public static void main(String[] args) throws Exception {
        // 获取Flink执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 设置并行度为1，确保数据处理的顺序性
        env.setParallelism(1);
        // 从Kafka中消费车辆数据
        DataStream<String> kafkaStream = KafkaUtil.consumerKafka(env, "vehicle-date-geohash");
//        kafkaStream.print();
        // 处理消费到的数据
        Processheadel(kafkaStream);

        env.execute("VehicleWindowRealtimeStatus");
    }

    /**
     * 处理车辆数据流
     * 该方法将车辆数据解析、分配时间戳和水位线、按车辆信息分组、窗口计算，并将结果写入ClickHouse
     * 从Kafka消费的车辆数据流
     */
    private static void Processheadel(DataStream<String> kafkaStream) {
        // 将消费到的JSON字符串解析为VehicleData对象
        SingleOutputStreamOperator<VehicleData> VehicleDataMap = kafkaStream.map(
                o -> JSON.parseObject(o, VehicleData.class)
        );
        // 为数据分配时间戳和水位线，基于事件时间处理
        SingleOutputStreamOperator<VehicleData> vehicleDataSingleOutputStreamOperator = VehicleDataMap.assignTimestampsAndWatermarks(WatermarkStrategy
                .<VehicleData>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                .withTimestampAssigner(
                        new SerializableTimestampAssigner<VehicleData>() {
                            @Override
                            public long extractTimestamp(VehicleData element, long recordTimestamp) {
                                // 使用车辆数据中的时间戳作为事件时间
                                return element.getTimestamp();
                            }
                        }
                )
        );
        // 按车辆信息分组，以便后续的窗口计算
        KeyedStream<VehicleData, VehicleData> vehicleDataVehicleDataKeyedStream = vehicleDataSingleOutputStreamOperator.keyBy(o -> o);
        // 定义一个基于事件时间的滚动窗口，窗口大小为1分钟
        WindowedStream<VehicleData, VehicleData, TimeWindow> window = vehicleDataVehicleDataKeyedStream.window(
                TumblingEventTimeWindows.of(Time.minutes(1))
        );
        // 定义窗口计算逻辑，将窗口开始时间、结束时间和车辆状态信息格式化为字符串输出
        SingleOutputStreamOperator<String> process = window.apply(
                new WindowFunction<VehicleData, String, VehicleData, TimeWindow>() {
                    @Override
                    public void apply(VehicleData vehicleData, TimeWindow window, Iterable<VehicleData> input, Collector<String> out) throws Exception {
                        // 将窗口开始和结束时间格式化为字符串
                        String window_start = DateTimeUtil.convertLongToString(window.getStart(), DateTimeUtil.DATE_TIME_FORMAT);
                        String window_end = DateTimeUtil.convertLongToString(window.getStart(), DateTimeUtil.DATE_TIME_FORMAT);
                        // 构造输出字符串，包含窗口信息和车辆状态信息
                        out.collect(window_start + "," +
                                window_end + "," +
                                vehicleData.getVin() + "," +
                                vehicleData.getSpeed() + "," +
                                vehicleData.getBatteryLevel() + "," +
                                vehicleData.getBatteryTemp() + "," +
                                vehicleData.getMotorTemp() + "," +
                                vehicleData.getChargingStatus() + "," +
                                vehicleData.getEnergyConsumption());
                    }
                }
        );
        // 将处理结果写入ClickHouse数据库
        JdbcUtil.sinkToClickhouseUpsert(process, "INSERT INTO vehicle_log.vehicle_status (window_start, window_end, vin, speed," +
                " batteryLevel, batteryTemp, motorTemp, chargingStatus, energyConsumption)\n" +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
    }
}

